package com.duobaoyu.dby.supply.biz.producer;

import com.alibaba.fastjson.JSON;
import com.duobaoyu.dby.channel.adapter.enums.BizScenarioEnum;
import com.duobaoyu.dby.supply.biz.processor.TransactionAfterPostProcessor;
import com.duobaoyu.dby.supply.biz.producer.message.OrderCancelMessage;
import com.duobaoyu.dby.supply.biz.producer.message.OrderPaymentTimeoutCancelMessage;
import com.duobaoyu.dby.supply.biz.service.queue.core.DistributionQueueMessage;
import com.duobaoyu.dby.supply.biz.service.queue.service.DistributionQueueJobService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author liyang
 * @version 1.0.0
 * @ClassName SupplyChainDistributionMessageProducer
 * @Description 延时消息生产者
 * @createTime 12:18:00 2023/10/07
 */
@Component
@RequiredArgsConstructor
public class SupplyChainDelayMessageProducer extends TransactionAfterPostProcessor {

    private final DistributionQueueJobService distributionQueueJobService;

	/**
	 * 取消渠道订单topic
	 */
	@Value("${delay.cancelChannelOrder.topicName}")
	private String delayCancelChannelOrderTopicName;

	/**
	 * 支付超时自动取消topic
	 */
	@Value("${delay.cancelPaymentTimeoutOrder.topicName}")
	private String cancelPaymentTimeoutOrderTopicName;

	/**
	 * 延迟取消渠道订单
	 *
	 * @param supplyTradeSn 交易单号
	 * @param orderSnList   订单号
	 * @param cancelBeforeOrderStatus 取消前订单状态
	 */
	public void channelOrderCancelSend(String supplyTradeSn, List<String> orderSnList, Integer cancelBeforeOrderStatus) {
		OrderCancelMessage cancelMessage = OrderCancelMessage
				.builder()
				.supplyTradeSn(supplyTradeSn)
				.orderSnList(orderSnList)
				.cancelBeforeOrderStatus(cancelBeforeOrderStatus)
				.build();
		this.execute(() -> distributionQueueJobService.send(new DistributionQueueMessage(delayCancelChannelOrderTopicName,
				BizScenarioEnum.DELAY_CANCEL_CHANNEL_ORDER.getValue(),
				null,
				1000L,
				JSON.toJSONString(cancelMessage))));
	}

	/**
	 * 支付超时自动取消消息
	 * @param orderSn 订单号
	 * @param delayTime 延迟时间毫秒
	 */
	public void paymentTimeoutAutoCancel(String orderSn, long delayTime) {
		OrderPaymentTimeoutCancelMessage autoCancelMessage = new OrderPaymentTimeoutCancelMessage();
		autoCancelMessage.setOrderSn(orderSn);
		this.execute(() -> distributionQueueJobService.send(new DistributionQueueMessage(cancelPaymentTimeoutOrderTopicName,
				BizScenarioEnum.DELAY_CANCEL_PAYMENT_TIMEOUT_ORDER.getValue(),
				orderSn,
				delayTime,
				JSON.toJSONString(autoCancelMessage))));
	}
}
